<?php


namespace app\component;


class ExcelComponent
{
    /**
     * @param $path string 文件路径
     * @return array
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \Exception
     */
    public function reader($path)
    {
        $content = [];
        $info = pathinfo($path);
        switch ($info['extension']) {
            case 'xlsx':
                $type = 'Xlsx';
                break;
            case 'xls':
                $type = 'Xls';
                break;
            case 'csv':
                $type = 'Csv';
                break;
            default:
                throw new \Exception('type is illegal,Only supported xlsx, xls, csv');
        }
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($type);
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($path);
        $worksheet = $spreadsheet->getActiveSheet();
        foreach ($worksheet->getRowIterator() as $row) {
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(FALSE);
            $row = [];
            foreach ($cellIterator as $cell) {
                $row[] = $cell->getValue();
            }
            $content[] = $row;
        }
        return $content;
    }
}